<template>
  <div>
    <el-button type="primary"  @click="showAddDialog"  icon="el-icon-plus">添加</el-button>

    <!-- el表格 -->
    <el-table border :data="trademarkList" style="width: 100%; margin: 20px 0">
      <el-table-column
        align="center"
        prop="prop"
        label="序号"
        type="index"
        width="80"
      >
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>
      <el-table-column label="品牌LOGO" width="width">
        <template slot-scope="{ row, $index }">
          <img style="width: 80px; height: 80px" :src="row.logoUrl" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="width">
        <template slot-scope="{ row, $index }">
          <el-button type="warning" size="mini" icon="el-icon-edit" @click="showUpdateDialog(row)"
            >修改</el-button
          >
          
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteDialog(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- el分页器 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="getTrademarkList"
      style="text-align: center"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      :total="total"
      :pager-count="7"
      layout="  prev, pager, next, jumper,->,sizes,total"
    >
    </el-pagination>

    <!-- eldailog对话框 -->
                                        <!-- 控制dailog弹出和隐藏 -->
    <el-dialog :title="tmForm.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
      <!-- el-form是专门用来收集数据的,
      el-from都会指定一个数据 ,
      el-from都会有一个item的项,
      一般一项就用来收集一个数据
      -->
      <el-form ref="tmForm" :model="tmForm" :rules="rules" style="width:80%">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="tmForm.tmName"  autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- 上传组件 -->
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg文件，且不超过2M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"  @click="addOrUpdateTrademark">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "TrademarkList",
  data() {
    var validateTmName = (rule, value, callback) => {
        if (value.length < 2 || value.length > 20) {
          callback(new Error('请输入长度在2-20之间的字符'));
        } else {
          callback();
        }
      };
    return {
      page: 1,
      limit: 3,
      total: 0,
      trademarkList: [],
      dialogFormVisible:false,
      imageUrl: '', //拷贝的upload内部的一个数据,后期用不用不知道
      tmForm:{
        tmName:'',
        logoUrl:''
      },
      rules: {
          tmName: [
            // tirgger 触发方式  验证时机
            // blur失去焦点  唱歌改变内容  整体验证的时候触发
            { required: true, message: '品牌名称必须有', trigger: 'blur' },
            // { min: 3, max: 5, message: '长度在 2 到 10 个字符', trigger: 'change' }
            { validator: validateTmName, trigger: 'blur' }
          ],
          logoUrl: [
            { required: true, message: '请选择品牌LOGO', trigger: 'change' }
          ]
        }
    };
  },
  mounted() {
    this.getTrademarkList();
  },
  methods: {
    async getTrademarkList(page = 1) {
      this.page = page;
      try {
        let result = await this.$API.trademark.getPageList(
          this.page,
          this.limit
        );
        if (result.code === 200 || result.code === 20000) {
          this.trademarkList = result.data.records;
          this.total = result.data.total;
        }
      } catch (error) {
        this.$message.error("请求获取品牌列表失败" + error.message);
      }
    },
    // 修改每页的数量
    handleSizeChange(size) {
      this.limit = size;
      this.getTrademarkList();
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw); //收集的本地图片地址
      // console.log(res,file,URL.createObjectURL(file.raw))
      this.tmForm.logoUrl = res.data
    },
    // 上传之前的回调函数,你不需要动
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    // 点击添加弹出dialog
    showAddDialog(){
      this.dialogFormVisible = true
      // 添加完成,取消再次点击,数据仍然存在的bug
      this.tmForm.tmName = ''
      this.tmForm.logoUrl = ''
    },
  // 点击修改弹出dialog
    showUpdateDialog(row){
      this.dialogFormVisible = true
      // 浅拷贝
      this.tmForm = {...row}
    },
  // 点击添加品牌
  addOrUpdateTrademark(){
      this.$refs.tmForm.validate(async(valid) => {
          if (valid) {
            // 获取请求所需要的参数
            let trademark = this.tmForm
            try {
              // 发请求
              await this.$API.trademark.addOrUpdate(trademark)
              // 提示
              this.$message.success(trademark.id?'修改成功':'添加成功')
              // 关闭dialog 回到列表页
              this.dialogFormVisible = false
              // 更新列表数据
              this.getTrademarkList(trademark.id?this.page:1)
            } catch (error) {
              this.$message.error(trademark.id?'修改失败':'添加失败' + error.message)
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    // 用$messageBox弹框删除品牌
    deleteDialog(row){
        this.$confirm(`你确定要删除${row.tmName}吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          try {
            await this.$API.trademark.delete(row.id)
            this.$message.success('删除品牌成功')
            this.getTrademarkList(this.trademarkList.length>1?this.page:this.page-1)
          } catch (error) {
            this.$message.error('删除失败' + error.message)
          }  

          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    }
  },
};
</script>

<style>
/* 不要加scoped */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>



